import datetime
import string
import urllib

import aiohttp
import aioredis
import lxml.html
import json
import asyncio
import time
import random
import logging
import sys
import os
from Crypto.Cipher import AES
import re
from faker import Faker
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from io import BytesIO
from PIL import Image
from pyzbar.pyzbar import decode

# sys.path.append(os.path.abspath('../'))


logger = logging.getLogger("cmcc")


def get_ts():
    return str(time.time()).replace('.', '')[:13]


async def cmcc10086_qrcode(usertel, amount, redis, pay_type, username, passwd, ip=None):
    faker = Faker(locale='zh_CN')
    # ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        "Referer": "https://shop.10086.cn/i/v1/res/numarea/13418071372?_=1559631289123",
        "Host": "shop.10086.cn"
        # 'Cookie': cookies
    }
    if ip:

        headers.update({
            'CLIENT-IP': ip,
            'X-FORWARDED-FOR': ip
        })
    res = await login(username, passwd, redis)
    if res['code'] != 0:
        return res

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    # aiohttp.TCPConnector(verify_ssl=False)
    if proxys:
        proxy = random.choice(list(proxys))
        conn = proxy or None
    else:
        conn = None
    # conn = None

    async with aiohttp.ClientSession(headers=headers) as session:
        session.cookie_jar.load('/app/log/cmcc_username/' + username)
        # url = 'https://shop.10086.cn/i/service/recharge/item/itemcollect_200_200_.html'
        # async with session.get(url) as resp:
        #     pass
        url = 'https://shop.10086.cn/i/v1/res/numarea/%s?_=%s' % (usertel, get_ts()) # 'https://shop.10086.cn/i/v1/res/numarea/13418071372?_=1559631289123'

        async with session.get(url, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {"code": 1}
            content = await resp.text(encoding='utf-8')
            prov_data = json.loads(content)
            logger.info(prov_data)
            if prov_data['retCode'] == '000000':
                prov_cd = prov_data['data']['prov_cd']
            else:
                return {"code": 1, 'message': prov_data['retMsg']}

        headers["Referer"] = 'https://shop.10086.cn/i/service/recharge/item/itemcollect_200_200_.html'
        # 获取优惠
        rule_params = {'amountFlag': 1,
                       'channel': '00',
                       'enableFlag': 1, 'enableType': 0,
                       'phoneNo': base64.b64encode(usertel.encode()).decode(),
                       'provCode': prov_cd,
                       'saleFlag': 1,
                       'saleQueryType': 2}
        url = 'https://shop.10086.cn/i/v1/pay/payrule/%s' % usertel
        amount = int(amount)
        async with session.post(url, json=rule_params, headers=headers, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                text = await resp.text()
                logger.error(text)
                return {"code": 1}
            rule_data = await resp.json()
            logger.info(rule_data)
            operateId = ''
            pay_amount = amount
            for rule in rule_data['data']['saleRules']:
                operateId = rule['operateId']
                if '9.98' in rule['saleName']:
                    operateId = rule['operateId']
                    pay_amount = amount * 0.998
                    break
                if '998' in rule['saleName']:
                    operateId = rule['operateId']
                    pay_amount = amount * 0.998
                    break
                elif '9.95' in rule['saleName']:
                    operateId = rule['operateId']
                    pay_amount = amount * 0.995
                    break
                elif '995' in rule['saleName']:
                    operateId = rule['operateId']
                    pay_amount = amount * 0.995
                    break

        # pay_amount = amount * 0.998
        pay_data = {'amount': pay_amount,
                    'channel': '00',
                    'chargeMoney': amount,
                    'choseMoney': amount,
                    'homeProv': prov_cd,
                    'numFlag': '0',
                    'operateId': operateId,
                    'source': ''}
        url = 'https://shop.10086.cn/i/v1/pay/saveorder/%s?provinceId=%s' % (usertel, prov_cd)
        headers["Host"] = "shop.10086.cn"
        headers["Origin"] = "https://shop.10086.cn"
        headers["Referer"] = "https://shop.10086.cn/i/?f=rechargecredit&mobileNo=%s&amount=%s" % (usertel, amount)
        headers["X-Requested-With"] = "XMLHttpRequest"

        async with session.post(url, json=pay_data, headers=headers, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {'code': 1}
            pay_rsp = await resp.json()
            logger.info(pay_rsp)

            if pay_rsp['retCode'] == '000000':
                pay_url = pay_rsp['data']['payUrl']
                orderid = pay_rsp['data']['orderId']
            else:
                if pay_rsp['retCode'] == "511012":
                    redis.sadd("konghao", usertel)
                return {'code': pay_rsp['retCode'], 'message': pay_rsp['retMsg']}
            async with session.get(pay_url) as resp:
                if resp.status != 200:
                    logger.error(resp.status)
                    return {'code': 1}
                content = await resp.text()
                root = lxml.html.fromstring(content)
                # qr_img = root.xpath('//img[@class="qrcode"]')[0]
                # img_url = "https://pay.shop.10086.cn/paygw/" + qr_img.attrib['src']
                # img_url = urllib.parse.urljoin(resp.url, qr_img)
                # logger.info(img_url)
                eles = root.xpath('//form[@id="payment"]/div/input')
                ali_data = {e.name: e.value for e in eles}

            url = 'https://shop.10086.cn/i/v1/pay/chargeorder/{0}'.format(username)


            ordermonth = datetime.datetime.now().strftime('%Y%m')
            data = {
                'payStartDate': ordermonth,
                'payEndDate': ordermonth,
                'numType': '',
                'queryType': '0',
                'orderStatus': '6',
                'pageNo': 1,
                '_': get_ts()
            }

            prov = ""
            async with session.get(url, params=data, proxy=conn) as rsp:
                text = await rsp.text()
                order_info = json.loads(text)
                if not order_info['data']['outList']:
                    return {"code": 1, "message": "未关联到账号"}
                for info in order_info['data']['outList']:
                    if info['orderId'] == orderid:
                        prov = info['provName']
                        break
            if not prov:
                return {"code": 1, "message": "未关联到账号"}

            if pay_type == "ALIH5":
                # pay_link = pay_url
                headers['User-Agent'] = 'Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36'
                headers['Referer'] = pay_url
                headers['Host'] = 'pay.shop.10086.cn'
                url = 'https://pay.shop.10086.cn/paygw/mobileAndBankPayH5'

                async with session.get(pay_url, headers=headers, proxy=conn) as resp:
                    content = await resp.text()
                    root = lxml.html.fromstring(content)
                    eles = root.xpath('//*[@id="itemForm"]//input')
                    alidata = {e.name: e.value for e in eles}
                    alidata['bankAbbr'] = 'ALIPAY'
                    # if pay_type == 'ALIH5':
                    #     alidata['bankAbbr'] = 'ALIPAY'
                    # else:
                    #     alidata['bankAbbr'] = 'WXPAY'
                    print(alidata)
                async with session.post(url, data=alidata, allow_redirects=False, proxy=conn) as resp:
                    pay_link = resp.headers['Location']
                    print(pay_link)
            # elif pay_type == "WXH5":
            #     url = 'https://pay.shop.10086.cn/paygw/mobileAndBankPayH5'
            #     ali_data['bankAbbr'] = 'WXPAY'
            #     headers['User-Agent'] = 'Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36'
            #     headers['Referer'] = pay_url
            #     headers['Host'] = 'pay.shop.10086.cn'
            #     async with session.post(url, data=ali_data, proxy=conn, headers=headers) as resp:
            #         if resp.status != 200:
            #             logger.error(resp.status)
            #             return {'code': 1}
            #
            #         content = await resp.text()
            #         pay_link = re.findall('"(weixin.*)"', content)[0]

            else:
                pay_link = pay_url
                # headers['Host'] = 'pay.shop.10086.cn'
                # headers['Referer'] = pay_url
                # url = 'https://pay.shop.10086.cn/paygw/mobileAndBankPayAjax'
                # ali_data['bankAbbr'] = 'WXPAY'
                # async with session.get(url, params=ali_data, headers=headers) as resp:
                #     if resp.status != 200:
                #         pay_link = ""
                #     else:
                #         content = await resp.text(encoding='gbk')
                #         obj = json.loads(content)
                #         pay_link = 'https://pay.shop.10086.cn/paygw/' + obj.get('url', "")
                #         logger.info(pay_link)
                # headers['Host'] = 'pay.shop.10086.cn'
                # headers['Referer'] = pay_url
                # async with session.get(pay_link, headers=headers) as resp:
                #     content = await resp.read()
                #     # logger.info(content)
                #     decode_result = decode(Image.open(BytesIO(content)))
                #     logger.info(decode_result[0].data)
                #     # logger.info(decode_result[0].data)
                #     pay_link = decode_result[0].data.decode()

            # print(pay_link, pay_url, pay_amount, amount, orderid, pay_url)
            return {'orderid': orderid, 'url': pay_url, 'qrcode': pay_link, 'code': 0, 'prov': prov}

async def aget_llqrcode(usertel, amount, redis):
    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        "Referer": "https://shop.10086.cn/i/v1/res/numarea/13418071372?_=1559631289123",
        "Host": "shop.10086.cn"
        # 'CLIENT-IP': ip,
        # 'X-FORWARDED-FOR': ip,
    }

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    # conn = None
    # logger.info("代理%s|%s", usertel, proxy)
    async with aiohttp.ClientSession(headers=headers) as session:
        url = 'https://shop.10086.cn/i/v1/res/numarea/%s?_=%s' % (usertel, get_ts())
        async with session.get(url, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {'retcode': '-1', 'message': '查询失败'}
            content = await resp.text(encoding='utf-8')
            prov_data = json.loads(content)
            logger.info(prov_data)
            if prov_data['retCode'] == '000000':
                prov_cd = prov_data['data']['prov_cd']
            else:
                return prov_data

        # 获取优惠
        rule_params = {'amountFlag': 1,
                       'channel': '00',
                       'enableFlag': 1, 'enableType': 0,
                       'phoneNo': base64.b64encode(usertel.encode()).decode(),
                       'provCode': prov_cd,
                       'saleFlag': 1,
                       'saleQueryType': 2}
        headers["Referer"] = url

        data = {
            "chargeCell": usertel,
            "flowType": "3",
            "payWay": "1",
            "channel": "00",
            "_": "%d" % (time.time() * 1000),
        }
        headers["Referer"] = "https://shop.10086.cn/i/?f=rechargegprs&mobileNo=%s&amount=%s" % (usertel, amount)
        url = 'https://shop.10086.cn/i/v1/pay/flow/goodslist/client'
        async with session.get(url, params=data, headers=headers, proxy=conn) as resp:

            rule_data = await resp.text()
            logger.info(rule_data)
            rule_data = json.loads(rule_data)
            rule_data = rule_data['data']['goodsList'][1]
            goods_id = rule_data['goodsId']
            goodsPrice = rule_data['cashPrice']
            orderPrice = goodsPrice
            discountId = ""
            productTraffic = rule_data['productTraffic']
            if rule_data.get('discountList'):
                discountCnt = rule_data['discountList'][0]['discountCnt']
                discountId = rule_data['discountList'][0]['marketId']
                orderPrice = '%.f' % (float(goodsPrice) * float(discountCnt)/100)
        BS = AES.block_size
        pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
        mode = AES.MODE_CBC
        cipher = AES.new(b'043AOQGK6ykklyZA', mode, b'043AOQGK6ykklyZA')
        en_text = cipher.encrypt(pad(usertel).encode())
        en_text = base64.b64encode(en_text)
        en_text = base64.b64encode(en_text).decode()
        logger.info(en_text)
        pay_data = {
            "discountId": discountId,
            'channel': '00',
            'chargeCell': base64.b64encode(usertel.encode()).decode(),
            'exchangeType': '1',
            'goodsId': goods_id,
            'goodsPrice': goodsPrice,
            'numFlag': '0',
            'orderPrice': orderPrice,
            'productTraffic': productTraffic,
            'userNum': '',
            'userType': '2'
        }
        url = 'https://shop.10086.cn/i/v1/pay/flow/submitPay/%s' % en_text
        print(url)
        headers["Host"] = "shop.10086.cn"
        headers["Origin"] = "https://shop.10086.cn"
        headers["Referer"] = "https://shop.10086.cn/i/?f=rechargegprs&mobileNo=%s&amount=%s" % (usertel, amount)
        headers["X-Requested-With"] = "XMLHttpRequest"

        async with session.post(url, json=pay_data, headers=headers, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                content = await resp.read()
                logger.info(content)
                return {'retcode': '-1', 'message': '查询失败'}
            pay_rsp = await resp.json()
            logger.info(pay_rsp)
            if pay_rsp['retCode'] in ("511012", "511014"):
                redis.sadd("konghao", usertel)
            return pay_rsp


async def cmcc10086_llqrcode(usertel, amount, redis, pay_type, username, passwd, ip=None):
    res = await aget_llqrcode(usertel, amount, redis)
    if res["retCode"] != "000000":
        logger.info("%s不可交费", usertel)
        return {'code': -1}
    faker = Faker(locale='zh_CN')
    # ip = faker.ipv4()
    url = 'https://shop.10086.cn/i/v1/res/numarea/%s?_=%s' % (usertel, get_ts())
    headers = {
        'User-Agent': faker.chrome(),
        "Referer": url,
        "Host": "shop.10086.cn"
        # 'Cookie': cookies
    }
    if ip:

        headers.update({
            'CLIENT-IP': ip,
            'X-FORWARDED-FOR': ip
        })
    res = await login(username, passwd, redis)
    if res['code'] != 0:
        return res

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    # aiohttp.TCPConnector(verify_ssl=False)
    if proxys:
        proxy = random.choice(list(proxys))
        conn = proxy or None
    else:
        conn = None
    # conn = None

    async with aiohttp.ClientSession(headers=headers) as session:
        session.cookie_jar.load('/app/log/cmcc_username/' + username)
        async with session.get(url, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {"code": 1}
            content = await resp.text(encoding='utf-8')
            prov_data = json.loads(content)
            logger.info(prov_data)
            if prov_data['retCode'] == '000000':
                prov_cd = prov_data['data']['prov_cd']
            else:
                return {"code": 1, 'message': prov_data['retMsg']}

        # pay_amount = amount * 0.998
        pay_data = {'amount': amount,
                    'channel': '00',
                    'chargeMoney': amount,
                    'choseMoney': amount,
                    'homeProv': prov_cd,
                    'source': ''}
        url = 'https://shop.10086.cn/i/v1/pay/savebroadorder/%s?provinceId=%s' % (usertel, prov_cd)
        headers["Host"] = "shop.10086.cn"
        headers["Origin"] = "https://shop.10086.cn"
        headers["Referer"] = "https://shop.10086.cn/i/?f=rechargecredit&mobileNo=%s&amount=%s" % (usertel, amount)
        headers["X-Requested-With"] = "XMLHttpRequest"

        async with session.post(url, json=pay_data, headers=headers, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {'code': 1}
            pay_rsp = await resp.json()
            logger.info(pay_rsp)

            if pay_rsp['retCode'] == '000000':
                pay_url = pay_rsp['data']['payUrl']
                orderid = pay_rsp['data']['orderId']
            else:
                if pay_rsp['retCode'] == "511012":
                    redis.sadd("konghao", usertel)
                return {'code': pay_rsp['retCode'], 'message': pay_rsp['retMsg']}

            url = 'https://shop.10086.cn/i/v1/pay/chargeorder/{0}'.format(username)
            ordermonth = datetime.datetime.now().strftime('%Y%m')
            data = {
                'payStartDate': ordermonth,
                'payEndDate': ordermonth,
                'numType': '2',
                'queryType': '0',
                'orderStatus': '6',
                'pageNo': 1,
                '_': get_ts()
            }

            prov = ""
            async with session.get(url, params=data, proxy=conn) as rsp:
                text = await rsp.text()
                order_info = json.loads(text)
                if not order_info['data']['outList']:
                    return {"code": 1, "message": "未关联到账号"}
                for info in order_info['data']['outList']:
                    if info['orderId'] == orderid:
                        prov = info['provName']
                        break
            if not prov:
                return {"code": 1, "message": "未关联到账号"}

            pay_link = pay_url
            return {'orderid': orderid, 'url': pay_url, 'qrcode': pay_link, 'code': 0, 'prov': prov}


async def cmcc_10086_query(order_id, redis, username, passwd, orderdate, numType=""):

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        # 'Cookie': cookies
    }

    res = await login(username, passwd, redis)
    if res['code'] != 0:
        return '9', '登陆失败'

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    if proxy:
        conn = proxy
    else:
        conn = None

    async with aiohttp.ClientSession(headers=headers) as session:
        session.cookie_jar.load('/app/log/cmcc_username/' + username)
        url = 'https://shop.10086.cn/i/v1/pay/chargeorder/{0}'.format(username)
        n = 1
        end_date = datetime.datetime.now().strftime('%Y%m')
        while n < 10:
            data = {
                'payStartDate': orderdate[:6],
                'payEndDate': end_date,
                'numType': numType,
                'queryType': '0',
                'orderStatus': '6',
                'pageNo': n,
                '_': get_ts()
            }
            async with session.get(url, params=data, proxy=conn) as rsp:
                text = await rsp.text()
                order_info = json.loads(text)
                logger.info(order_info)
                if not order_info['data']['outList']:
                    return '9', "未找到记录"
                for info in order_info['data']['outList']:
                    if info['orderId'] == order_id:
                        if info['orderStatus'] == '0':
                            orderstate = '9'
                            message = "未支付2"
                        elif info['orderStatus'] == '1':
                            orderstate = '9'
                            message = "超时未支付"
                        elif info['orderStatus'] == '5':
                            orderstate = '1'
                            message = '充值失败'
                        elif info['orderStatus'] == '4':
                            orderstate = '0'
                            message = "充值成功"
                        elif info['orderStatus'] == '2':
                            orderstate = '9'
                            message = '支付成功'
                        else:
                            orderstate = '9'
                            message = '未知'
                        return orderstate, message
            n += 1


async def cmcc_100862_query(orderid, url, redis, username, passwd):
    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        'CLIENT-IP': ip,
        'X-FORWARDED-FOR': ip,
        "Referer": url
    }

    res = await login(username, passwd, redis)
    if res['code'] != 0:
        return '9', '登陆失败'

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    if proxy:
        conn = proxy
    else:
        conn = None
    async with aiohttp.ClientSession(headers=headers) as session:
        session.cookie_jar.load('/app/log/cmcc_username/' + username)
        url = 'https://pay.shop.10086.cn/paygw/fnpay/%s-20.html' % orderid
        async with session.get(url, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return '9', '请求出错'
            query_url = str(resp.url)

        params = urllib.parse.urlparse(query_url).query
        params = '%s&_=%s' % (params, get_ts())
        url = 'https://shop.10086.cn/i/v1/pay/paycallback?' + params
        headers['Host'] = 'shop.10086.cn'
        headers['Referer'] = query_url
        headers['X-Requested-With'] = 'XMLHttpRequest'
        async with session.get(url, headers=headers, proxy=conn) as resp:
            res_rsp = await resp.json()
            logger.info(res_rsp)
            if res_rsp['data']['status'] == '0':
                orderstate = '0'
            else:
                orderstate = '8'
            return orderstate, res_rsp['data']['payDate']

def decrypt(key, ciphertext):
    # key = RSA.importKey(pri)

    cipher = PKCS1_v1_5.new(key)
    _message = cipher.encrypt(ciphertext)
    return base64.b64encode(_message).decode()


async def get_code(content):
    headers = {"Authorization": "APPCODE 370107e384e1409b9af32352c20e6100"}
    data = {
        'v_pic': base64.b64encode(content).decode(),
        'v_type': 'ne6'
    }
    # print(data)
    async with aiohttp.ClientSession(headers=headers) as session:
        url = 'http://yzm.cqjianjiao.com/yzm'
        async with session.post(url, data=data) as rsp:
            rsp_obj = await rsp.text()
            rsp_obj = json.loads(rsp_obj)
            logger.info(rsp_obj)
            if rsp_obj['errCode'] == 0:
                v_code = rsp_obj['v_code']
                with open('/app/log/captcha/' + v_code + '.png', 'wb') as f:
                    f.write(content)
                return rsp_obj['v_code']

            return None



async def get_code2(content):
    data = {
        'image_base64': base64.b64encode(content).decode(),
        'app_id': '379809080&VIP@Mzc5ODA5MDgwJlZJUA==',
        # 'image_code': '0000'
    }
    async with aiohttp.ClientSession() as session:
        url = 'https://nmd-ai.juxinli.com/ocr_captcha'
        async with session.post(url, json=data) as rsp:
            rsp_obj = await rsp.text()
            rsp_obj = json.loads(rsp_obj)
            logger.info(rsp_obj)
            if rsp_obj['errorcode'] == 0:
                v_code = rsp_obj['string']
                return v_code

            return None

async def report_err_code(content):
    data = {
        'image_base64': base64.b64encode(content).decode(),
        'app_id': '379809080',
        'image_code': '0000',
        'action': 'report_image'
    }
    async with aiohttp.ClientSession() as session:
        url = 'https://nmd-ai.juxinli.com/ocr_captcha'
        async with session.post(url, json=data) as rsp:
            rsp_obj = await rsp.text()
            rsp_obj = json.loads(rsp_obj)
            logger.info(rsp_obj)
            return None

def gen_nonce_str(N=32):
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))


async def reg(email, raw_password, redis):
    key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsgDq4OqxuEisnk2F0EJFmw4xKa5IrcqEYHvqxPs2CHEg2kolhfWA2SjNuGAHxyDDE5MLtOvzuXjBx/5YJtc9zj2xR/0moesS+Vi/xtG1tkVaTCba+TV+Y5C61iyr3FGqr+KOD4/XECu0Xky1W9ZmmaFADmZi7+6gO9wjgVpU9aLcBcw/loHOeJrCqjp7pA98hRJRY+MML8MK15mnC4ebooOva+mJlstW6t/1lghR8WNV8cocxgcHHuXBxgns2MlACQbSdJ8c6Z3RQeRZBzyjfey6JCCfbEKouVrWIUuPphBL3OANfgp0B+QG31bapvePTfXU48TYK0M5kE+8LgbbWQIDAQAB"
    pub = RSA.importKey(base64.b64decode(key))
    login_url = 'https://login.10086.cn/registersubmit.htm'
    # raw_password = gen_nonce_str(N=8)
    password = decrypt(pub, raw_password.encode())
    newpassword = decrypt(pub, raw_password.encode())
    data = {
        'loginName': email,
        'userPassword': password,
        'newPasswordRepeat': newpassword,
        'inputCode': '',
        'channelId': '',
        'timestamp': get_ts()
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        'Host': 'login.10086.cn',
        'Referer': 'https://login.10086.cn/html/register/register.html'

    }
    proxys = await redis.smembers('un_proxy', encoding='utf-8')

    # aiohttp.TCPConnector(verify_ssl=False)
    if proxys:
        proxy = random.choice(list(proxys))
        conn = proxy or None
    else:
        conn = None
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get('https://login.10086.cn/html/register/register.html', headers=headers,
                               proxy=conn) as rsp:
            headers['Referer'] = 'https://login.10086.cn/html/register/register.html'
            async with session.get('https://login.10086.cn/captchazh.htm?type=05&timestamp=' + get_ts(),
                                   headers=headers) as resp:
                text = await resp.read()
                captcha = await get_code2(text)

        data['inputCode'] = captcha
        async with session.post(login_url, data=data, headers=headers, proxy=conn) as rsp:
            content = await rsp.text()
            res = json.loads(content)
            print(content)
            if res['errorCode'] == "0":
                async with session.get('https://login.10086.cn/registerSuccess.htm', headers=headers) as rsp:
                    await rsp.text()
                session.cookie_jar.save('/app/log/reg_username/' + email)
                with open('/app/log/captcha2/' + captcha + '.png', 'wb') as f:
                    f.write(text)
                return {"code": 0, "message": res['errorMsg'], "password": raw_password}
            else:
                if res['errorCode'] == "5":
                    with open('/app/log/err_captcha/' + captcha + '.png', 'wb') as f:
                        f.write(text)

                return {"code": res['errorCode'], 'message': res['errorMsg']}


async def re_send(email, redis):
    proxys = await redis.smembers('un_proxy', encoding='utf-8')

    # aiohttp.TCPConnector(verify_ssl=False)
    if proxys:
        proxy = random.choice(list(proxys))
        conn = proxy or None
    else:
        conn = None
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        'Host': 'login.10086.cn',
        'Referer': 'https://login.10086.cn/html/register/register.html'

    }
    data = {
        'type': 'sch'
    }
    async with aiohttp.ClientSession(headers=headers) as session:
        session.cookie_jar.load('/app/log/reg_username/' + email)
        async with session.post('https://login.10086.cn/sendemail.htm', data=data, proxy=conn) as rsp:
            content = await rsp.text()
            print(email, content)
            return content


async def login(username, passwd, redis):
    captcha = ""
    data = {
        'accountType': '02',
        'account': username,
        'timestamp': get_ts()
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        'Host': 'login.10086.cn',
        'Referer': 'https://login.10086.cn/html/login/login.html'
    }

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    # aiohttp.TCPConnector(verify_ssl=False)
    if proxys:
        proxy = random.choice([p for p in proxys if '@' not in p and '16817' not in p])
        # proxy = random.choice(list(proxys))
        conn = proxy or None
    else:
        conn = None
    async with aiohttp.ClientSession(headers=headers) as session:
        if os.path.isfile('/app/log/cmcc_username/' + username):
            session.cookie_jar.load('/app/log/cmcc_username/' + username)
        url = 'https://shop.10086.cn/i/v1/auth/loginfo?_=' + get_ts()
        async with session.get(url) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {"code": 1}
            content = await resp.text(encoding='utf-8')
            logger.info(content)
            login_data = json.loads(content)
            if login_data['retCode'] == '000000':
                return {"code": 0, 'message': login_data['retMsg']}
        url = 'https://login.10086.cn/login.html?channelID=12003&backUrl=https://shop.10086.cn/i/service/recharge/item/itemcollect_100_100_.html'
        async with session.get(url, headers=headers, proxy=conn) as rsp:
            pass
        url = 'https://login.10086.cn/needVerifyCode.htm'
        async with session.get(url, params=data, headers=headers, proxy=conn) as rsp:
            res = await rsp.text()
            res = json.loads(res)
            logger.info(res)
        cap_text = None
        if res['needVerifyCode'] != "0":
            url = 'https://login.10086.cn/captchazh.htm?type=12&timestamp=' + get_ts()
            async with session.get(url, headers=headers) as resp:
                cap_text = await resp.read()
                captcha = await get_code2(cap_text)

        key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsgDq4OqxuEisnk2F0EJFmw4xKa5IrcqEYHvqxPs2CHEg2kolhfWA2SjNuGAHxyDDE5MLtOvzuXjBx/5YJtc9zj2xR/0moesS+Vi/xtG1tkVaTCba+TV+Y5C61iyr3FGqr+KOD4/XECu0Xky1W9ZmmaFADmZi7+6gO9wjgVpU9aLcBcw/loHOeJrCqjp7pA98hRJRY+MML8MK15mnC4ebooOva+mJlstW6t/1lghR8WNV8cocxgcHHuXBxgns2MlACQbSdJ8c6Z3RQeRZBzyjfey6JCCfbEKouVrWIUuPphBL3OANfgp0B+QG31bapvePTfXU48TYK0M5kE+8LgbbWQIDAQAB"
        pub = RSA.importKey(base64.b64decode(key))
        data = {
            'accountType': '02',
            'account': username,
            'password': decrypt(pub, passwd.encode()),
            'pwdType': '03',
            'smsPwd': '',
            'inputCode': captcha,
            'backUrl': 'https://shop.10086.cn/i/?f=home',
            'rememberMe': '1',
            'channelID': '12003',
            'loginMode': '01',
            'protocol': 'https:',
            'timestamp': get_ts()
        }
        url = 'https://login.10086.cn/login.htm'
        async with session.get(url, params=data, headers=headers, proxy=conn) as rsp:
            text = await rsp.text()
            res = json.loads(text)
            if res['code'] != '0000':
                return {'code': 1, 'message': res.get('desc')}
            logger.info(text)

        data = {
            'backUrl': 'https://shop.10086.cn/i/service/recharge/item/itemcollect_100_100_.html',
            'artifact': res['artifact']
        }
        url = 'https://shop.10086.cn/i/v1/auth/getArtifact'
        async with session.get(url, params=data, headers=headers, proxy=conn) as rsp:
            # text = await rsp.text()
            # print(text)
            pass
        url = 'https://shop.10086.cn/i/v1/auth/loginfo?_=' + get_ts()
        async with session.get(url, headers=headers, proxy=conn) as resp:
            if resp.status != 200:
                logger.error(resp.status)
                return {"code": 1}
            content = await resp.text(encoding='utf-8')
            login_data = json.loads(content)
            logger.info(login_data)
            if login_data['retCode'] != '000000':
                return {"code": 1, 'message': login_data['retMsg']}
            else:
                if cap_text:
                    with open('/app/log/captcha2/' + captcha + '.png', 'wb') as f:
                        f.write(cap_text)
                session.cookie_jar.save('/app/log/cmcc_username/' + username)
                return {"code": 0, 'message': login_data['retMsg']}


async def order_cancel(orderid, username, passwd, redis):
    data = {"orderId": orderid, "channel": "00", "loginNo": username}
    url = "https://shop.10086.cn/i/v1/pay/ordercancel"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        'Host': 'shop.10086.cn',
        'Origin': 'https://shop.10086.cn',
        # 'Referer': 'https://shop.10086.cn/i/?f=home&welcome=1550135499444'
    }

    res = await login(username, passwd, redis)
    if res['code'] != 0:
        return res

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    # aiohttp.TCPConnector(verify_ssl=False)
    if proxys:
        proxy = random.choice([p for p in proxys if '@' not in p and '16817' not in p])
        # proxy = random.choice(list(proxys))
        conn = proxy or None
    else:
        conn = None

    async with aiohttp.ClientSession(headers=headers) as session:
        if os.path.isfile('/app/log/cmcc_username/' + username):
            session.cookie_jar.load('/app/log/cmcc_username/' + username)
        async with session.post(url, json=data, headers=headers, proxy=conn) as rsp:
            text = await rsp.text()
            res = json.loads(text)
            logger.info(res)
            if res['retCode'] == '000000':
                return {"code": 0, 'message': res['retMsg']}
            else:
                return {"code": 1, 'message': res['retMsg']}


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    now = time.time()
    redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
    # redis = ""
    # cookies = 'item_province=100; item_city=100; item_range=; tkpp=kdcajqyjqo; inx=myorders; inx2=returnorderqry; ssologinprovince=; WT_FPC=id=23dbff69e56502f3dac1538043213753:lv=1549961944695:ss=1549961852638; collect_id=dmb5kt42vo50w4wymex39ji4wm94sryb; CmLocation=100|100; CmProvid=bj; PHPSESSID=4nd0vbugrbq2i2403l43kcpa06; cart_code_key=4nd0vbugrbq2i2403l43kcpa06; mobile=; lgToken=947f95868bdd41b9809948b493d10523; CaptchaCode=NLZpJP; sendflag=20190212165848271275; cmccssotoken=7afc623ce4444099878d39587ba8b021@.10086.cn; c=7afc623ce4444099878d39587ba8b021; verifyCode=199cc5b54b392e6ab6fac393a8318c5d549b4a53; jsessionid-echd-cpt-cmcc-jt=07F17FCC2F366AD07CCFAAA5FF72CC50; rdmdmd5=F2D71070F113D146B47777CF731941FB; is_login=true'
    # cookies = 'CITY_INFO=100|10;CaptchaCode=oRPYZR;rdmdmd5=B5B7EE47AC02C63788CD69CEAC51E7E0;cmccssotoken=e28ba3ab19414c07906d1931d8e4035b@.10086.cn;is_login=true;defaultloginuser_e=izr73fwOUuimT7R+YElqbgprS80H91DDkW4D+wQu8VCMaCnvRGGKQ5C9HR/8Dc7uj1IFDhmZtbn+Tt3RMK2EorJXug4x5eJABBYN3u7gM7GO4zh6cFe8ZtNzJZ6j+NISB1of8n2wO8CcJ5IJHjWKkg==;c=e28ba3ab19414c07906d1931d8e4035b;verifyCode=199cc5b54b392e6ab6fac393a8318c5d549b4a53'
    task = asyncio.ensure_future(cmcc10086_llqrcode("13418071372", "10", redis, 'ALI', "shenzh147666@163.com", 'you12345678'))
    # task = asyncio.ensure_future(cmcc_10086_query("442837492165298394", "13418071372", "", "shenzh147666@163.com", '20190212'))
    # task = asyncio.ensure_future(reg("gkauu8@163.com", "epay1688", redis))
    # task = asyncio.ensure_future(login("shenzh147666@163.com", "you12345678", redis))
    # task = asyncio.ensure_future(order_cancel("442837851168782961", "shenzh147666@163.com", redis))
    print(loop.run_until_complete(task))
    print(time.time() - now)
    loop.close()
